package taskTracker.ui.lwuit;

import taskTracker.Project;
import taskTracker.Task;

import com.sun.lwuit.Command;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Form;
import com.sun.lwuit.List;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;

/**
 * Displays a list of tasks in a project
 * @author aseldawy
 *
 */
public class TaskListUI extends Form implements ActionListener {

	/**Command for adding new task*/
	private Command cmdAdd = new Command("Add");
	/**Command for editing selected task*/
	private Command cmdEdit = new Command("Edit");
	/**Command for deleting selected task*/
	private Command cmdDelete = new Command("Delete");
	/**Command to issue a delete*/
	private final Command cmdBack = new Command("Back");

	/**The main list that holds tasks*/
	private List lstTasks;
	
	/**A form used to create or edit tasks*/
	private TaskForm taskForm;
	
	/**The screen that was displayed before this*/
	private final Form previous;
	
	/**Last issued command to differentiate Add from Edit*/
	private Command lastCommand;
	
	public TaskListUI(Project taskList, Form previous) {
		this.previous = previous;
		super.addCommand(cmdAdd);
		super.addCommand(cmdEdit);
		super.addCommand(cmdDelete);
		super.addCommand(cmdBack);
		super.setBackCommand(cmdBack);
		
		super.addComponent(lstTasks = new List(taskList.getTasks()));
		
		super.addCommandListener(this);
		
	}

	public void actionPerformed(ActionEvent ae) {
		if (ae.getCommand() == cmdAdd) {
			getTaskForm(null).show();
			this.lastCommand = cmdAdd;
		} else if (ae.getCommand() == cmdEdit) {
			getTaskForm((Task) lstTasks.getSelectedItem()).show();
		} else if (taskForm != null && ae.getCommand() == taskForm.cmdOk) {
			Task task = taskForm.getTask();
			if (this.lastCommand == cmdAdd) {
				lstTasks.addItem(task);
			}
			lstTasks.repaint();
			this.show();
		} else if (taskForm != null && ae.getCommand() == taskForm.cmdCancel) {
			this.show();
		} else if (ae.getCommand() == cmdBack) {
			previous.show();
		} else if (ae.getCommand() == cmdDelete) {
			if (Dialog.show("Confirmation", "Are you sure you want to delete?", "OK", "Cancel")) {
				lstTasks.getModel().removeItem(lstTasks.getSelectedIndex());
			}
		}
	}

	/**
	 * Creates or retrieves a task list form
	 */
	private Form getTaskForm(Task task) {
		// Lazy initialization
		if (this.taskForm == null) {
			this.taskForm = new TaskForm();
			this.taskForm.addCommandListener(this);
		}
		this.taskForm.setTask(task);
		return this.taskForm;
	}
}
